package com.project.myPackage.controller;
import com.project.myPackage.common.R;
import com.project.myPackage.entity.EIException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;

/**
 * 上传文件映射表
 */
//不建议使用这个类，因为上传图片之后，获取路径访问的是缓存，所以只能重启项目才能访问新上传的图片
@RestController
@RequestMapping("file")
public class FileController {
	@Value("${server.port}")
	private String  downloadPath="";
	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")

	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new EIException("上传文件不能为空");
		}

		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		File path = new File(System.getProperty("user.dir"));
		if (!path.exists()) {
			path = new File("");
		}

		File upload = new File(path.getAbsolutePath(), "/src/main/resources/static/upload/");
		if (!upload.exists()) {
			upload.mkdirs();
		}

		String fileName = new Date().getTime() + "." + fileExt;
		File dest = new File(upload.getAbsolutePath() + "/" + fileName);

		file.transferTo(dest);
		downloadPath = ServletUriComponentsBuilder.fromCurrentContextPath().toUriString();
		// 返回访问路径，假设服务访问域名为 http://localhost:3000
		String fileUrl =  downloadPath + "/file/download/" + fileName;

		return R.success(fileUrl, "上传成功");
	}
     //下面两种方式都需要重启idea，才访问新上传的图片
	/**
	 * 访问图片
	 */
	/**
	 * 直接访问图片（支持浏览器直接显示或下载）
	 */
//	@GetMapping("/download/{fileName:.+}")
//	public ResponseEntity<byte[]> serveImage(@PathVariable String fileName) {
//		try {
//			// 获取 static/upload 目录路径
//			File path = new File(ResourceUtils.getURL("classpath:static").getPath());
//			if (!path.exists()) {
//				path = new File("");
//			}
//
//			File uploadDir = new File(path, "upload/");
//			if (!uploadDir.exists()) {
//				return ResponseEntity.notFound().build();
//			}
//
//			File file = new File(uploadDir, fileName);
//			if (!file.exists()) {
//				return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File not found".getBytes());
//			}
//
//			// 自动检测 MIME 类型（如 image/png, image/jpeg 等）
//			String contentType = Files.probeContentType(file.toPath());
//			if (contentType == null || !contentType.startsWith("image/")) {
//				contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
//			}
//
//			byte[] imageBytes = Files.readAllBytes(file.toPath());
//
//			return ResponseEntity.ok()
//					.header(HttpHeaders.CONTENT_TYPE, contentType)
//					.body(imageBytes);
//
//		} catch (IOException e) {
//			e.printStackTrace();
//			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
//		}
//	}

	@Autowired
	private ResourceLoader resourceLoader;

	@GetMapping("/download/{fileName:.+}")
	public ResponseEntity<byte[]> serveImage(@PathVariable String fileName) {
		try {
			Resource resource = resourceLoader.getResource("classpath:static/upload/" + fileName);
			if (!resource.exists()) {
				return ResponseEntity.notFound().build();
			}

			String contentType = Files.probeContentType(resource.getFile().toPath());
			if (contentType == null || !contentType.startsWith("image/")) {
				contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
			}

			byte[] imageBytes = FileCopyUtils.copyToByteArray(resource.getInputStream());

			return ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_TYPE, contentType)
					.body(imageBytes);

		} catch (IOException e) {
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
		}
	}

}
